﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using Fuse8.DomainFramework.Domain;

namespace Fuse8.DomainFramework.DataAccess.SqlDatabase
{
	internal class EntityToSqlMappingService : IEntityToSqlMappingService
	{
		private readonly SqlConnection _connection;
		private readonly Dictionary<string, IList<SqlColumn>> _entityColumns = new Dictionary<string, IList<SqlColumn>>();
		public EntityToSqlMappingService(SqlConnection connection)
		{
			_connection = connection;
		}

		public string GetSqlNameByEntityName<T>(string entityName)
		{
			return GetSqlNameByEntityName(typeof (T), entityName);
		}

		public string GetSqlNameByEntityName(Type type, string entityName)
		{
			return GetSqlNameByEntityName(type, entityName, null);
		}

		public string GetSqlNameByEntityName(Type type, string entityName, string alias)
		{
			var key = string.Format("{0}{1}", _connection.ConnectionString, type.Name);
			if (!_entityColumns.ContainsKey(key))
			{
				_entityColumns[key] = SchemaBuilder.Current.GetColumns(type, _connection);
			}
			var column = _entityColumns[key].FirstOrDefault(p => p.EntityPropertyName == entityName);
			var result = column == null ? entityName : column.SqlColumnName;
			if (!string.IsNullOrEmpty(alias))
			{
				result = string.Format("{0}.[{1}]", alias, result);
			}
			return result;
		}
	}
}